package com.alex.space.commons.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Alex
 *         Created by Alex on 2017/12/21.
 */
public class TokenUtils {

    static String secret = "privateKey";

    public static String createToken() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>(2);
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)
                .withClaim("name", "alex")
                .withClaim("age", "20")
                .withClaim("password", "123456")
                .sign(Algorithm.HMAC256(secret));
        return token;
    }

    public static void verifyToken(String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
                .build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        System.out.println(claims.get("name").asString());
    }

    public static void main(String[] args) throws Exception {
        String token = createToken();
        System.out.println(token);

        verifyToken(token);

    }

}
